package com.ttg.web.controller.open;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ttg.common.entities.JobResult;
import com.ttg.common.enums.ErrorCodeEnums;
import com.ttg.common.enums.TaskEnum;
import com.ttg.common.enums.TaskStatusEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.common.utils.JsonUtils;
import com.ttg.common.utils.RequestParamsManager;
import com.ttg.model.dto.AdminViewDTO;
import com.ttg.model.pojo.TaskInfo;
import com.ttg.model.vo.open.JobVo;
import com.ttg.web.config.CustomHttpServletRequestWrapper;
import com.ttg.web.dao.TaskInfoDao;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Objects;

/**
 * @ClassName JobController
 * @Description job任务 http入口
 * @Author CZW
 * @Date 2022/8/3
 * @Version 1.0
 **/

@Api("job任务")
@RestController
@RequestMapping("/call")
@Slf4j
public class JobController {

    @Autowired
    private TaskInfoDao taskInfoDao;

    @ApiOperation("job")
    @RequestMapping("/job")
    public String index(HttpServletRequest request) {
        CustomHttpServletRequestWrapper requestWrapper = null;
        try {
            requestWrapper = new CustomHttpServletRequestWrapper(request);
        } catch (IOException e) {
            return JobResult.fail(e.getMessage()).toString();
        }
        String data = requestWrapper.getBody();
        String jobName = null;
        String jobParam = null;
        log.info("任务参数:{}", data);
        try {
            HashMap<String, String> map = parseParams(data);
            JobVo jobVo = BeanUtil.mapToBean(map, JobVo.class, true);
            jobName = jobVo.getJobName();
            jobParam = jobVo.getJobParam();
            if (ObjectUtil.isNull(jobName) && StringUtils.isEmpty(jobName)) {
                throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
            }
            if (ObjectUtil.isNotNull(jobParam) && StringUtils.isNotEmpty(jobParam)) {
                jobParam = jobParam.replace("douHao", ",");
            }
        } catch (Exception e) {
            log.error(e.getMessage().toString());
            return JobResult.fail(e.getMessage()).toString();
        }
        log.info("任务名称：{}---------------任务参数：{}", jobName, jobParam);
        IJobHandler iJobHandler = XxlJobExecutor.loadJobHandler(jobName);
        if (Objects.isNull(iJobHandler)) {
            return JobResult.defaultFail().toString();
        }
        try {
            XxlJobContext xxlJobContext = new XxlJobContext(-1, jobParam, null, -1, -1);
            XxlJobContext.setXxlJobContext(xxlJobContext);
            iJobHandler.execute();
        } catch (Exception e) {
            log.error("任务名称：{}--------------任务参数：{}-----------异常：{}", jobName, jobParam, e);
            return JobResult.fail(e.getMessage()).toString();
        } finally {
            XxlJobContext.setXxlJobContext(null);
        }
        return JobResult.success().toString();
    }

    @RequestMapping("/resultQuery")
    public String resultQuery(HttpServletRequest request) {
        CustomHttpServletRequestWrapper requestWrapper = null;
        try {
            requestWrapper = new CustomHttpServletRequestWrapper(request);
        } catch (IOException e) {
            return JobResult.fail(e.getMessage()).toString();
        }
        String data = requestWrapper.getBody();
        String jobName = null;
        String jobParam = null;
        try {
            HashMap<String, String> map = parseParams(data);
            JobVo jobVo = BeanUtil.mapToBean(map, JobVo.class, true);
            jobName = jobVo.getJobName();
            jobParam = jobVo.getJobParam();
            if (ObjectUtil.isNull(jobName) && StringUtils.isEmpty(jobName)) {
                throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
            }
            if (ObjectUtil.isNotNull(jobParam) && StringUtils.isNotEmpty(jobParam)) {
                jobParam = jobParam.replace("douHao", ",");
            }
        } catch (Exception e) {
            log.error(e.getMessage().toString());
            return JobResult.fail(e.getMessage()).toString();
        }
        log.info("resultQuery任务参数：{}---------------任务参数：{}", jobName, jobParam);

        TaskInfo taskInfo = taskInfoDao.getByTag(jobName);
        if (Objects.isNull(taskInfo)){
            //任务标签不存在
            throw new BaseException(ErrorCodeEnums.TASK_TAG_ABSENT.getErrcode(),ErrorCodeEnums.TASK_TAG_ABSENT.getMsg());
        }
        JobResult jobResult = new JobResult();
        jobResult.setOutCode(taskInfo.getTaskStatus().toString());
        if (taskInfo.getTaskStatus().equals(TaskStatusEnum.FAIL.getStatus())){
            jobResult.setOutMest(taskInfo.getTaskMessage());
        }
        return jobResult.toString();
    }

    private HashMap<String, String> parseParams(String str) {
        HashMap<String, String> map = new HashMap<>();
        String[] split = str.split("&");
        try {
            for (String s : split) {
                String[] split1 = s.split("=");
                String key = URLDecoder.decode(split1[0], "UTF-8");
                String value = URLDecoder.decode(split1[1], "UTF-8");
                map.put(key, value);
            }
        } catch (Exception e) {
            throw new BaseException(ErrorCodeEnums.PARAM_VALIDATION_FAIL);
        }
        return map;
    }
}
